package com.tinem.platform.service.data.api;

import cn.hutool.core.codec.Base64;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.util.HttpMethod;
import com.tinem.platform.module.pojo.vo.error.UserException;
import com.tinem.platform.module.starter.sdk.MessageCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(value = "constants")
@RestController
@RequestMapping("/constants")
public class ConstantsApi {

    @PostMapping("/export.api")
    @ResponseBody
    @ApiOperation(value = "导出所有常量", httpMethod = HttpMethod.POST, notes = "暂无")
    public Object export(@RequestBody String req){
        try(InputStream inputStream = new ByteArrayInputStream(Base64.decode(req))){
            return export(inputStream);
        } catch (IOException e) {
            log.warn("",e);
            throw new UserException(MessageCode.ERROR_COMMONS_UNKNOWN);
        }
    }
    public JSONObject export(InputStream excelInputStream){
        JSONObject root = new JSONObject();
        ExcelReader reader = ExcelUtil.getReader(excelInputStream);
        List<Map<String,Object>> readAll = reader.readAll();
        readAll.forEach(line->{
            String key = String.valueOf(line.get("key"));
            String _desc = String.valueOf(line.get("说明"));
            if(!root.containsKey(key)){
                JSONObject lineObject = new JSONObject();
                lineObject.put("desc",_desc);
                JSONObject value = new JSONObject();
                lineObject.put("value",value);
                root.put(key,lineObject);
            }
            JSONObject lineObject = root.getJSONObject(key);
            JSONObject valueObject = new JSONObject();
            valueObject.put("zh_cn",String.valueOf(line.get("zh_cn")));
            valueObject.put("zh_tw",String.valueOf(line.get("zh_tw")));
            valueObject.put("ja_jp",String.valueOf(line.get("ja_jp")));
            valueObject.put("ko_kr",String.valueOf(line.get("ko_kr")));
            valueObject.put("en_us",String.valueOf(line.get("en_us")));
            lineObject.getJSONObject("value").put(String.valueOf(line.get("value")),valueObject);
        });
        return root;
    }
}
